﻿<%@ WebHandler Language="C#" Class="RbFocusContainerProcessHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

/**
 * Description: 热表重点转工批次进度维护
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer:zhunan
 * create Date:2022-08-09
 */

public class RbFocusContainerProcessHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetAcceptedContainerShipData"://查询已接收转工批次数据
                    GetAcceptedContainerShipData(context);
                    break;
                case "getData":
                    getData(context);
                    break;
                case "insertData":
                    insertData(context);//添加MES数据
                    break;
                case "updateData":
                    updateData(context);//更新
                    break;
                case "deleteData":
                    deleteData(context);//删除
                    break;
                case "insertNotMESData":
                    insertNotMESData(context);//添加非MES数据
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    void getData(HttpContext context)
    {
        string sql = @"
SELECT t.*
FROM (
SELECT rb.factoryname fromfactoryname,
       '热表分厂' tofactoryname,
       rb.productname,rb.productdesc productdescription,
       rb.containername,rb.qty,rb.workflowstepname,
       rb.receivedate ToAcceptDate,
       to_char(rb.needfinishdate,'yyyy/mm/dd') needcompletedate,
       NVL(rb.finishdate,t.completedate) completedate,
       CASE WHEN NVL(rb.finishdate,t.completedate) IS NULL THEN '未完成'
            WHEN NVL(rb.finishdate,t.completedate) IS NOT NULL THEN '已完成' 
       END status,
       rb.currentprocess,
       e.fullname createemployee,rb.createdate,e2.fullname modifyemployee,rb.modifydate,rb.rbfocuscontainerprocessid,rb.sourcetype 
FROM rbfocuscontainerprocess rb
LEFT JOIN employee e ON e.employeeid = rb.createemployeeid
LEFT JOIN employee e2 ON e2.employeeid = rb.modifyemployeeid
LEFT JOIN r_shipboard_jijia@mesreport t ON t.containername = rb.containername AND t.workflowstepname = rb.workflowstepname
WHERE rb.isuse = 0
";
        //主制分厂
        if (context.Request["factoryname"] != null && context.Request["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND rb.factoryname = '{0}'", context.Request["factoryname"].ToString());
        }
        //批次号
        if (context.Request["containername"] != null && context.Request["containername"].ToString() != "")
        {
            sql += string.Format(" AND rb.containername LIKE '%{0}%'", context.Request["containername"].ToString());
        }
        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND rb.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }
        //热表接收时间
        if (context.Request["recivedateStart"] != null && context.Request["recivedateStart"].ToString() != "")
        {
            sql += string.Format(" AND rb.receivedate >= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateStart"].ToString());
        }
        if (context.Request["recivedateEnd"] != null && context.Request["recivedateEnd"].ToString() != "")
        {
            sql += string.Format(" AND rb.receivedate <= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateEnd"].ToString());
        }
        //数据来源
        if (context.Request["sourcetype"] != null && context.Request["sourcetype"].ToString() != "全部")
        {
            string sourcetype = context.Request["sourcetype"].ToString();
            if (sourcetype == "1")
            {
                sql += " AND rb.sourcetype = 1";
            }
            else
            {
                sql += " AND rb.sourcetype = 2";
            }
        }

        sql += @"
) t
WHERE 1=1
";
        //完成状态
        if (context.Request["status"] != null && context.Request["status"].ToString() != "全部")
        {
            string status = context.Request["status"].ToString();
            if (status == "已完成")
            {
                sql += " AND t.status = '已完成'";
            }
            else
            {
                sql += " AND t.status = '未完成'";
            }
        }
        
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    // 查询已转工排产，且热表已接收但未完成数据
    void GetAcceptedContainerShipData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        string sql = @"
SELECT t.factoryname fromfactoryname,t.tofactoryname,t.productname,t.productdescription,t.containername,cci.qty,t.workflowstepname,
       to_char(t.recivedate,'yyyy/mm/dd') ToAcceptDate,
       to_char(t.needcompletedate,'yyyy/mm/dd') needcompletedate
FROM r_shipboard_jijia@mesreport t
LEFT JOIN containercurrentinfo cci ON cci.containername = t.containername
LEFT JOIN rbfocuscontainerprocess c ON t.containername = c.containername AND t.workflowstepname = c.workflowstepname
WHERE c.rbfocuscontainerprocessid IS NULL AND t.receiver IS NOT NULL AND t.completedate IS NULL
";
        sql += string.Format(" AND t.tofactoryname = '{0}'", m_UserInfo.Factory);
        //主制分厂
        if (context.Request["factoryname"] != null && context.Request["factoryname"].ToString() != "")
        {
            sql += string.Format(" AND t.factoryname = '{0}'", context.Request["factoryname"].ToString());
        }
        //批次号
        if (context.Request["containername"] != null && context.Request["containername"].ToString() != "")
        {
            sql += string.Format(" AND t.containername LIKE '%{0}%'", context.Request["containername"].ToString());
        }
        //件号
        if (context.Request["productname"] != null && context.Request["productname"].ToString() != "")
        {
            sql += string.Format(" AND t.productname LIKE '%{0}%'", context.Request["productname"].ToString());
        }
        //热表接收时间
        if (context.Request["recivedateStart"] != null && context.Request["recivedateStart"].ToString() != "")
        {
            sql += string.Format(" AND TRUNC(t.recivedate) >= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateStart"].ToString());
        }
        if (context.Request["recivedateEnd"] != null && context.Request["recivedateEnd"].ToString() != "")
        {
            sql += string.Format(" AND TRUNC(t.recivedate) <= to_date('{0}','yyyy-mm-dd')", context.Request["recivedateEnd"].ToString());
        }
        uMESPagingDataDTO paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(context.Request.Form["pageNumber"].ToString());//页码
        paraPage.PageSize = Convert.ToInt32(context.Request.Form["PageSize"].ToString());//每页页数
        paraPage.strSQL = sql;
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataColumn col in result.DBTable.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    //添加来源为MES的数据
    void insertData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectData"].ToString());
            string processText = context.Request.Form["processText"].ToString();
            string sourcetype = context.Request.Form["sourcetype"].ToString();//数据来源MES
            string createemployeeid = m_UserInfo.EmployeeID.ToString();
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = @"
INSERT INTO rbfocuscontainerprocess(createemployeeid,currentprocess,containername,workflowstepname,
qty,productname,productdesc,receivedate,needfinishdate,finishdate,factoryname,sourcetype,rbfocuscontainerprocessid,createdate,isuse)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',to_date('{7}','yyyy/mm/dd hh24:mi:ss'),to_date('{8}','yyyy/mm/dd'),NULL,'{9}','{10}','{11}',SYSDATE,0)
";
                sql = string.Format(sql, createemployeeid,//创建人
                                         processText,//加工进度
                                         dr["containername"].ToString(),//批次号
                                         dr["workflowstepname"].ToString(),//工序名称
                                         dr["qty"].ToString(),//批次数量
                                         dr["productname"].ToString(),//件号
                                         dr["productdescription"].ToString(),//件号名称
                                         dr["toacceptdate"].ToString(),//接收时间
                                         dr["needcompletedate"].ToString(),//要求完成时间
                                         dr["fromfactoryname"].ToString(),//分厂
                                         sourcetype,//数据来源
                                         Guid.NewGuid().ToString());//唯一id

                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //添加数据来源非MES数据
    void insertNotMESData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["postData"].ToString());
            string createemployeeid = m_UserInfo.EmployeeID.ToString();
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = @"
INSERT INTO rbfocuscontainerprocess(createemployeeid,currentprocess,containername,workflowstepname,
qty,productname,productdesc,receivedate,needfinishdate,factoryname,sourcetype,finishdate,rbfocuscontainerprocessid,createdate,isuse)
VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',to_date('{7}','yyyy/mm/dd hh24:mi:ss'),to_date('{8}','yyyy/mm/dd'),'{9}','{10}',to_date('{11}','yyyy/mm/dd'),'{12}',SYSDATE,0)";

                sql = string.Format(sql, createemployeeid,//创建人
                                         dr["currentprocess"].ToString(),//加工进度
                                         dr["containername"].ToString(),//批次号
                                         dr["workflowstepname"].ToString(),//工序名称
                                         dr["qty"].ToString(),//批次数量
                                         dr["productname"].ToString(),//件号
                                         dr["productdescription"].ToString(),//件号名称
                                         dr["toacceptdate"].ToString(),//接收时间
                                         dr["needcompletedate"].ToString(),//要求完成时间
                                         dr["fromfactoryname"].ToString(),//分厂
                                         dr["sourcetype"].ToString(),//数据来源
                                         dr["finishdate"].ToString(),//完成时间
                                         Guid.NewGuid().ToString());//唯一id
                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //更新
    void updateData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["selectData"].ToString());
            string processText = context.Request.Form["processText"].ToString();
            string finishdate = context.Request.Form["finishdate"].ToString();//完成时间
            string needfinishdate = context.Request.Form["needfinishdate"].ToString();//要求完成时间
            if (finishdate != "")
            {
                finishdate = finishdate.Split(' ')[0];
            }
            if (needfinishdate != "")
            {
                needfinishdate = needfinishdate.Split(' ')[0];
            }
            string modifyemployeeid = m_UserInfo.EmployeeID.ToString();
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                if (dr["completedate"].ToString() != "")
                {
                    continue;
                }
                //非MES数据
                if (dr["sourcetype"].ToString() == "2" && finishdate != "")
                {
                    sql = @"
update rbfocuscontainerprocess t SET t.modifyemployeeid = '{0}',
                               t.modifydate = sysdate,t.currentprocess = '{1}',
                               t.finishdate = to_date('{2}','yyyy/mm/dd'),
                               t.needfinishdate = to_date('{3}','yyyy/mm/dd')
WHERE  t.rbfocuscontainerprocessid = '{4}'";
                    if (needfinishdate == "")
                    {
                        needfinishdate = dr["needcompletedate"].ToString().Split(' ')[0];
                    }
                    if (dr["completedate"].ToString() != "")
                    {
                        finishdate = dr["completedate"].ToString().Split(' ')[0];
                    }
                    sql = string.Format(sql, modifyemployeeid, processText, finishdate, needfinishdate, dr["rbfocuscontainerprocessid"].ToString());
                    int insertResult = DatabaseHelper.ExecuteSql(sql);
                }
                else
                {
                    sql = @"
update rbfocuscontainerprocess t SET t.modifyemployeeid = '{0}',
                                     t.modifydate = sysdate,
                                     t.currentprocess = '{1}',
                                     t.needfinishdate = to_date('{2}','yyyy/mm/dd')
WHERE  t.rbfocuscontainerprocessid = '{3}'";
                    if (needfinishdate == "")
                    {
                        needfinishdate = dr["needcompletedate"].ToString().Split(' ')[0];
                    }
                    sql = string.Format(sql, modifyemployeeid, processText, needfinishdate, dr["rbfocuscontainerprocessid"].ToString());
                    int insertResult = DatabaseHelper.ExecuteSql(sql);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }

    //删除
    void deleteData(HttpContext context)
    {
        if (m_UserInfo == null)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "当前未登录", DBTable = null }));
        }
        else
        {
            DataTable dtPostData = JsonConvert.DeserializeObject<DataTable>(context.Request.Form["willBeDeleteData"].ToString());
            string sql = "";
            foreach (DataRow dr in dtPostData.Rows)
            {
                sql = string.Format("DELETE rbfocuscontainerprocess t WHERE  t.rbfocuscontainerprocessid = '{0}'", dr["rbfocuscontainerprocessid"].ToString());
                int insertResult = DatabaseHelper.ExecuteSql(sql);
            }
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = true, Message = "", DBTable = null }));
        }
    }
}